$(function () {
    // $.support.cors = true;

    // var STR_HOST = 'http://42.121.52.125';
    var STR_HOST = 'http://www.100msm.com';
    var currTag = '';
    STR_URLBASE_VOTE = STR_HOST + '/item/aysnProcessSelected.htm',
        STR_URLBASE_GET_CANDIDATES = STR_HOST + '/item/selectCompareItems.htm',
        STR_URLBASE_GET_TOPS = STR_HOST + '/100msm/item/topItemsList.htm',
        NUM_MAX_DESC = 140;

    /**
     * @func 计算单字节字数，双字节算两个字
     * @param {String} str
     * @return {Number}
     */
    function countSingleByteWords(str) {
        var arr1, arr2, re;

        if (typeof str === 'string') {
            arr1 = str.match(/[x00-xff]/g) || [];
            arr2 = str.match(/[^x00-xff]/g) || [];
            re = arr1.length + arr2.length * 2;
        } else {
            re = 0;
        }

        return re;
    }

    /**
     * @func 截断字符串，返回x个单字节数的内容
     * @param {String} str
     * @param {Number} numberOfSingleByteWords
     * @return {String}
     */
    function cutWordsOff(str, numberOfSingleByteWords) {
        var re, count, index;

        if (typeof str === 'string') {
            if (typeof numberOfSingleByteWords === 'number') {
                count = numberOfSingleByteWords;
                index = 0;
                for (var len = str.length; index < len && count > 1; index++) {
                    if (/[x00-xff]/.test(str.charAt(index))) {
                        // 单字节
                        count = count - 1;
                    } else if (/[^x00-xff]/.test(str.charAt(index))) {
                        // 双字节
                        count = count - 2;
                    }
                }
                if (count != 1 || !/[x00-xff]/.test(str[index])) {
                    index--;
                }
                re = str.substring(0, index + 1);
            } else {
                re = str;
            }
        } else {
            re = '';
        }

        return re;
    }

    var voteWrapper = $('#vote');
    var voteCandidates = $('#vote .item');
    voteCandidates.each(function (index, domNode) {
        var voteCandidate = $(domNode),
        // onHover = voteCandidate.find('.item-onhover'),
            btn = voteCandidate.find('.item-btn a'),
        // 宝贝描述
            itemDesc = voteCandidate.find('.item-description p'),
            itemDescStr = itemDesc.html();

        // 截断宝贝描述
        if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
            itemDesc.prop('title', itemDescStr);
            itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
        }

        voteCandidate.hover(function () {
            voteCandidate.addClass('active');
        }, function () {
            voteCandidate.removeClass('active');
        });

        voteCandidate.click(function (ev) {
            var target = $(ev.target);

            if (!target.hasClass('btn-buy') && !target.hasClass('btn-collect')) {
                var arr = voteWrapper.attr('data-id').split(','),
                    url = STR_URLBASE_VOTE + '?winnerItemId=' + arr[0] + '&loserItemId=' + arr[1],
                    hxr;
                ev.preventDefault();
                hxr = $.getJSON(url).success(function (data) {
                    if (!data.success) {
                        throw new Error('fail to vote...')
                    }
                    // 请求新的投票对象
                    var hxr2 = $.ajax({
                        url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
                        dataType: 'json',
                        cache: false,
                        success: function (data, textStatus, jqXHR) {
                            var arr = data.result;
                            voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
                            voteCandidates.each(function (index, domNode) {
                                var voteCandidate = $(domNode),
                                    itemDesc = voteCandidate.find('.item-description p'),
                                    itemDescStr = arr[index].description;

                                // 描述
                                if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
                                    itemDesc.prop('title', itemDescStr);
                                    itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
                                } else {
                                    itemDesc.html(itemDescStr);
                                }
                                // 标题
                                voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
                                // 价格
                                voteCandidate.find('.item-price .price-figure').html(arr[index].price);
                                // 图片
                                voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
                                // 地址
                                voteCandidate.find('.btn-buy').prop('href', arr[index].url);
                            });
                        },
                        error: function (jqXHR, textStatus, errorThrown) {

                        },
                        complete: function (jqXHR, textStatus) {

                        }
                    });
                });
            }
        });
    });
    $('#skip').click(function (ev) {
        ev.preventDefault();
        var arr = voteWrapper.attr('data-id').split(',');
        // 请求新的投票对象
        $.ajax({
            url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                var arr = data.result;
                voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
                voteCandidates.each(function (index, domNode) {
                    var voteCandidate = $(domNode),
                        itemDesc = voteCandidate.find('.item-description p'),
                        itemDescStr = arr[index].description;

                    // 描述
                    if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
                        itemDesc.prop('title', itemDescStr);
                        itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
                    } else {
                        itemDesc.html(itemDescStr);
                    }
                    // 标题
                    voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
                    // 价格
                    voteCandidate.find('.item-price .price-figure').html(arr[index].price);
                    // 图片
                    voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
                    // 地址
                    voteCandidate.find('.btn-buy').prop('href', arr[index].url);
                });
            },
            error: function (jqXHR, textStatus, errorThrown) {

            },
            complete: function (jqXHR, textStatus) {

            }
        });
    });
    var hxr3 = $.ajax({
        url: STR_URLBASE_GET_TOPS,
        dataType: 'json',
        cache: false,
        success: function (data, textStatus, jqXHR) {
            var htmlStr = '';
            $.each(data.result, function (index, item) {
                if (index == data.result.length - 1) {
                    htmlStr += '<li class="last">';
                } else {
                    htmlStr += '<li>';
                }
                htmlStr += '<div class="item">';
                htmlStr += '<div class="item-pic"><a href="' + item.url + '" target="_blank"><img src="' + item.image + '_170x170.jpg"/></a></div>';
                htmlStr += '<p class="item-title" title="' + item.title + '">' + item.title + '</p>';
                htmlStr += '<p class="item-count">已得票：' + item.vote + '</p>';
                htmlStr += '</div>';
                htmlStr += '</li>';
            });
            $('#tops ul').html(htmlStr);
        },
        error: function (jqXHR, textStatus, errorThrown) {
        },
        complete: function (jqXHR, textStatus) {
        }
    });
    // 标签
    var currTagEl = $('#vote-tags .active a');
    $('#vote-tags a').click(function (ev) {
        var target = ev.target,
            targetEl = $(target),
            id = targetEl.attr('data-id') || '';

        ev.preventDefault();
        if (id != currTagEl.attr('data-id')) {
            currTagEl.parent().removeClass('active');
            currTagEl = targetEl;
            currTag = id;
            currTagEl.parent().addClass('active');

            // ajax
            var arr = voteWrapper.attr('data-id').split(',');
            // 请求新的投票对象
            $.ajax({
                url: STR_URLBASE_GET_CANDIDATES + (currTag ? '?tag=' + currTag : ''),
                dataType: 'json',
                cache: false,
                success: function (data, textStatus, jqXHR) {
                    var arr = data.result;
                    voteWrapper.attr('data-id', arr[0].id + ',' + arr[1].id);
                    voteCandidates.each(function (index, domNode) {
                        var voteCandidate = $(domNode),
                            itemDesc = voteCandidate.find('.item-description p'),
                            itemDescStr = arr[index].description;

                        // 描述
                        if (countSingleByteWords(itemDescStr) > NUM_MAX_DESC) {
                            itemDesc.prop('title', itemDescStr);
                            itemDesc.html(cutWordsOff(itemDescStr, NUM_MAX_DESC) + '...');
                        } else {
                            itemDesc.html(itemDescStr);
                        }
                        // 标题
                        voteCandidate.find('.item-title .item-title-wrapper').html(arr[index].title);
                        // 价格
                        voteCandidate.find('.item-price .price-figure').html(arr[index].price);
                        // 图片
                        voteCandidate.find('.item-pic img').prop('src', arr[index].image + '_310x310.jpg');
                        // 地址
                        voteCandidate.find('.btn-buy').prop('href', arr[index].url);
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {

                },
                complete: function (jqXHR, textStatus) {

                }
            });
        }
    });
    // toplist
    $('#top-list li').hover(function () {
        $(this).addClass('active');
    },function () {
        $(this).removeClass('active');
    }).click(function (ev) {
            if (ev.target.nodeName != 'A') {
                window.open($(this).find('.btn-buy').prop('href'));
            }
        });

});
